package com.mayblackcat.dy.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    //一重MD5
    private static String code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }

    //二重MD5
    public static String md5(String src){
        return DigestUtils.md5Hex(code(src));
    }

    //盐值
    private static final String salt=new String("ad14dcg5ffg56fef");

    //一次MD5加密
    public static String inputPassToFormPass(String inputPassword){
        String str=salt.charAt(6)+inputPassword+salt.charAt(12);
        str=salt.charAt(9)+str+salt.charAt(15);
        return md5(str);
    }

    //二次MD5加密
    public static String FormPassToDBPass(String formPassword){
        String str=salt.charAt(4)+formPassword+salt.charAt(7);
        str=salt.charAt(13)+str+salt.charAt(5);
        return md5(str);
    }

    //数据库加密
    public static String inputPassToDBPass(String inputPassword){
        String formPassword=MD5Util.inputPassToFormPass(inputPassword);
        String DBPassword=MD5Util.FormPassToDBPass(formPassword);
        return DBPassword;
    }
//    public static void main(String[] args) {
//        System.out.println(MD5Util.inputPassToDBPass("123"));
//        System.out.println(MD5Util.FormPassToDBPass("c04ce2579187d0c7dbe40c4c6f225c61"));
//        System.out.println(MD5Util.inputPassToFormPass("123"));
//
//    }

}
